package com.example.coffeeseller_2.model.communicate;


import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.example.coffeeseller_2.model.MachineConfig.MachineInitState;
import com.example.coffeeseller_2.model.MachineConfig.QRMsger;
import com.example.coffeeseller_2.model.beans.DealRecorder;
import com.example.coffeeseller_2.model.beans.MachineConfig;
import com.example.coffeeseller_2.model.beans.StateItemBean;
import com.example.coffeeseller_2.model.beans.openAndCloseBean;
import com.example.coffeeseller_2.model.beans.stateBean;
import com.example.coffeeseller_2.model.contentprovider.ApplicationConstance;
import com.example.coffeeseller_2.model.databases.DealOrderInfoManager;
import com.example.coffeeseller_2.model.factory.FragmentEnum;
import com.example.coffeeseller_2.model.factory.FragmentFactory;
import com.example.coffeeseller_2.model.helper.ClearMachine;
import com.example.coffeeseller_2.model.helper.CheckCurMachineState;
import com.example.coffeeseller_2.model.httputils.JsonUtil;
import com.example.coffeeseller_2.model.listenner.MessageReceviedListener;
import com.example.coffeeseller_2.model.listenner.MsgTransListener;
import com.example.coffeeseller_2.model.listenner.OnMachineCheckCallBackListener;
import com.example.coffeeseller_2.model.parse.PayResult;
import com.example.coffeeseller_2.utils.JinzhiSwitcher;
import com.example.coffeeseller_2.utils.MyLog;
import com.example.coffeeseller_2.utils.SecondToDate;
import com.example.coffeeseller_2.utils.Waiter;
import com.example.coffeeseller_2.views.HomeActivity;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import cof.ac.inter.CoffMsger;
import cof.ac.inter.MachineState;
import cof.ac.inter.Result;


public class TaskService extends Service implements MqttCallback, IMqttActionListener {
    private static MqttClient client;
    private MqttConnectOptions options;
    private String userName = "admin";
    private String passWord = "password";
    private OnMachineCheckCallBackListener mOnMachineCheckCallBackListener;
    static String TAG = "TaskService";
    static Handler mHandler;
    Timer mTimer = null;
    private TimerTask mTimerTask = null;
    public static final long RUN_PERIOD = 60000; //发送消息的间隔  一分钟发一次
    public static final long CLEAR_MACHINE_PERIOD = 4 * 60 * 60 * 1000; //4个小时清洗间隔4 * 60 * 60 * 1000


    static TaskService mInstance;


    public TaskService() {

    }

    public void dealHandler() {
        mHandler = new Handler(Looper.getMainLooper()) {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.obj == null) {
                    Log.d(TAG, "lost connect");
                    ReSubMqtt();
                } else {

                    JSONObject msgObject = (JSONObject) msg.obj;
                    Log.d(TAG, "收到消息  msg is " + msgObject.toString());
                    try {
                        switch (msgObject.getString("msgType")) {
                            case "payResult":
                                PayResult payResult = PayResult.getPayResult(msg.obj.toString());
                                if (msgTransListener != null) {
                                    Log.d(TAG, " msg Arrived ");
                                    msgTransListener.onMsgArrived(payResult);
                                } else {
                                    Log.d(TAG, "msgTransListener = null");
                                }
                                Log.d(TAG, "收到了支付类消息 ::::");
                                break;
                            case "updateFormulaType":

                                Log.d(TAG, "updateFormulaType  =  " + MachineConfig.getCurrentState());


                                if (messageReceviedListener != null) {
                                    //  messageReceviedListener.getMsgType(formulaObject.getString("formulaID"));//formulaID
                                    messageReceviedListener.getMsgType(msgObject.toString());
                                    MyLog.d(TAG, "messageReceviedListener  come");
                                }


                                break;
                            case "machineOrder":
                                if (messageReceviedListener != null)
                                    messageReceviedListener.getMsgType("machineOrder");
                                break;
                            case "relayType":
                                Log.d(TAG, "收到回执 uuid is " + msgObject.getString("msgId"));
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        };
    }


    private void checkSubSuccess() {
        int count = 3;
        while (count >= 0) {
            //当MQTT处于断开状态时进入循环判断开始计算

            if (!isConnected()) {
                if (count == 0) {
                    mOnMachineCheckCallBackListener.MQTTSubcribeFailed();
                    tagMachineCheckResult();//如果三次检测还是失败 则直接标记为订阅失败
                    break;
                } else {
                    count--;  //如果当前没有连接上对检测次数减一
                }


                Log.d(TAG, "获取了 topic 但是订阅失败，当前剩余count次数为: " + count);


            } else {
                startTimer();
                if (mOnMachineCheckCallBackListener != null) {
                    mOnMachineCheckCallBackListener.MQTTSubcribeSuccess();
                    MachineInitState.SUB_MQTT_STATE = MachineInitState.NORMAL;
                }
                tagMachineCheckResult();
                break;
            }
            Waiter.doWait(3000);//如果没有连接上,则等待5秒后机器判断
        }

    }

    private void tagMachineCheckResult() {
        if (MachineInitState.CHECK_OPENMAINCTRL == MachineInitState.NORMAL && MachineInitState.CHECK_MACHINECODE == MachineInitState.NORMAL && MachineInitState.SUB_MQTT_STATE == MachineInitState.NORMAL && MachineInitState.GET_FORMULA == MachineInitState.NORMAL) {
            if (mOnMachineCheckCallBackListener != null) {
                mOnMachineCheckCallBackListener.MachineCheckEnd(true);
            }

        } else {
            if (mOnMachineCheckCallBackListener != null) {
                mOnMachineCheckCallBackListener.MachineCheckEnd(false);
            }

        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public static synchronized TaskService getInstance() {
        if (mInstance == null) {
            mInstance = new TaskService();
        }
        return mInstance;
    }

    public void start(OnMachineCheckCallBackListener mOnMachineCheckCallBackListener) {
        if (mOnMachineCheckCallBackListener != null) {
            this.mOnMachineCheckCallBackListener = mOnMachineCheckCallBackListener;
        }
        Log.d("连接中", ".......");
        if (isConnected()) {
            Log.d("连接中", "current MQtt is connected");
            if (client != null) {
                try {
                    client.disconnect();

                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }

            subcribeMqtt();
        } else {
            Log.d("连接中", "current MQtt is not connected");
            subcribeMqtt();
        }


    }

    private void ReSubMqtt() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // host为主机名，clientid即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存

                    client = new MqttClient(MachineConfig.getTcpIP(), MachineConfig.getMachineCode(), new MemoryPersistence());
                    //  client = new MqttClient("tcp://119.23.71.185:61619", MachineConfig.getMachineCode(), new MemoryPersistence());

                    // MQTT的连接设置
                    options = new MqttConnectOptions();
                    // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
                    options.setCleanSession(true);
                    // 设置连接的用户名
                    options.setUserName(userName);
                    // 设置连接的密码
                    options.setPassword(passWord.toCharArray());
                    // 设置超时时间 单位为秒
                    options.setConnectionTimeout(10);
                    // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
                    options.setKeepAliveInterval(20);
                    //   options.setWill();
                    // 设置回调
                    client.setCallback(new TaskService());
                    Log.d(TAG, "topicip is " + MachineConfig.getTcpIP());
                    MqttTopic topic = client.getTopic(MachineConfig.getTcpIP());
                    // setWill方法，如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
                    Map<String, Object> bytejson = new HashMap<>();
                    bytejson.put("msgId", UUID.randomUUID().toString());
                    bytejson.put("msgType", "willType");
                    bytejson.put("machineCode", MachineConfig.getMachineCode());
                    bytejson.put("sendTime", SecondToDate.getDateToString(System.currentTimeMillis()));
                    Log.d(TAG, "byteJson = " + bytejson.toString());
                    options.setWill(topic, JsonUtil.mapToJson(bytejson).getBytes(), 2, true);
                    client.connect(options);
                    // 订阅消息
                    int[] Qos = {1, 1};
                    if (MachineConfig.getTopic().equals("") || MachineConfig.getTopic().equals("null")) {
                        mOnMachineCheckCallBackListener.MQTTSubcribeFailed();
                        return;
                    }
                    String[] topic1 = {MachineConfig.getTopic() + "#", "client/coffee/sc/#"};
                    //  String[] topic1 = {"client/coffee/20180509140000001/#", "client/coffee/sc/#"};
                    Log.d(TAG, topic1[0]);
                    client.subscribe(topic1, Qos);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void subcribeMqtt() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                init();
            }
        }).start();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        mInstance = this;
        dealHandler();
    }

    public void breakClient() {
        Log.d("断开", ".......");
        if (client.isConnected()) {
            try {
                client.disconnect();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

    }

    public boolean isConnected() {
        return client != null && client.isConnected();
    }

    private void init() {
        try {
            // host为主机名，clientid即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存

            client = new MqttClient(MachineConfig.getTcpIP(), MachineConfig.getMachineCode(), new MemoryPersistence());
//            client = new MqttClient("tcp://192.168.1.105:61613", MachineConfig.getMachineCode(), new MemoryPersistence());
            // MQTT的连接设置
            options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(userName);
            // 设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //   options.setWill();
            // 设置回调
            client.setCallback(new TaskService());
            Log.d(TAG, "topicip is " + MachineConfig.getTcpIP());
            MqttTopic topic = client.getTopic(MachineConfig.getTcpIP());//
            // setWill方法，如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
            Map<String, Object> bytejson = new HashMap<>();
            bytejson.put("msgId", UUID.randomUUID().toString());
            bytejson.put("msgType", "willType");
            bytejson.put("machineCode", MachineConfig.getMachineCode());
            bytejson.put("sendTime", SecondToDate.getDateToString(System.currentTimeMillis()));

            Log.d(TAG, "bytejson= " + bytejson.toString());
            options.setWill(topic, JsonUtil.mapToJson(bytejson).getBytes(), 2, true);
            client.connect(options);
            // 订阅消息
            int[] Qos = {1, 1};
            if (MachineConfig.getTopic().equals("") || MachineConfig.getTopic().equals("null")) {
                mOnMachineCheckCallBackListener.MQTTSubcribeFailed();
                return;
            }

            Log.d(TAG, "topic = " + MachineConfig.getTopic());
            String[] topic1 = {MachineConfig.getTopic() + "#", "client/coffee/sc/#"};//
//            String[] topic1 = {"client/coffee/20180822130000001/#", "client/coffee/sc/#"};
            Log.d(TAG, topic1[0]);
            client.subscribe(topic1, Qos);

        } catch (Exception e) {
            Log.e(TAG, "connect err " + e.getMessage());
            e.printStackTrace();
        }
        checkSubSuccess();
    }

    @Override
    public void connectionLost(Throwable throwable) {
        Log.d(TAG, "connectionLost :" + throwable.toString());
        mHandler.sendEmptyMessage(0);
    }

    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        JSONObject object = new JSONObject(new String(mqttMessage.getPayload()));
        Message msg = new Message();
        msg.obj = object;
        mHandler.sendMessage(msg);

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //   MyLog.d(TAG, "TaskService has been started");
        return super.onStartCommand(intent, flags, startId);

    }

    public void startTimer() {
        if (!hasTimerTask()) {
            if (isConnected()) {
                Log.d(TAG, "订阅成功" + "开始发送消息");
                createTimerTask();
            }

        }
    }

    private MsgTransListener msgTransListener;

    public void SetOnMsgListener(MsgTransListener msgTransListener) {

        MyLog.d(TAG, "SetOnMsgListener   ");
        this.msgTransListener = msgTransListener;
    }

    private MessageReceviedListener messageReceviedListener;

    public void setOnMessageReceviedListener(MessageReceviedListener listener) {
        messageReceviedListener = listener;
    }

    /**
     * 版本检测
     */

    public void stopService() {

        stopSelf();
        destroyTimerTask();
    }

    private boolean hasTimerTask() {

        return !(mTimer == null || mTimerTask == null);
    }

    private void createTimerTask() {

        if (mTimer == null) {

            mTimer = new Timer(true);
        }
        if (mTimerTask == null) {

            mTimerTask = new TimerTask() {

                long COUNT = 0;

                @Override
                public void run() {
                    MyLog.d(TAG, "timertask is been doing");
                    COUNT++;
                    //videoScreenCheck();//开关屏检测

                    //	LocalDataBaseUtil.deleteOutDateItem();

                    sendStateMsg();


                    if (COUNT % 3 == 0) {//本地交易记录上传


                        sendLocDealMsg();
                    }

                    if (COUNT % 4 == 0) {//删除本地交易记录

                        DealOrderInfoManager.getInstance(mInstance).deleteIfSizeOver200(200);
                    }
                  /*  if (COUNT % 120 == 0) {//版本检测

                        manageVersion();
                    }*/

                    clearMachine();
                }
            };
            mTimer.schedule(mTimerTask, 0, RUN_PERIOD);
        }

    }

    /*
    * 如果机器不忙，4个小时清洗
    * */
    private void clearMachine() {
        /*
        * 压盖
        * */
        boolean canClean = !CheckCurMachineState.getInstance().isMachineBusy()
                && FragmentFactory.curPage == FragmentEnum.ChooseCupNumFragment
                && !ApplicationConstance.getInstance().isHasCoffeeSelected()
                && !CheckCurMachineState.getInstance().getMachineState().isWasteLiquidInRightPlace();

      /*
      * 不压盖
      * */
     /*   boolean canClean = !CheckCurMachineState.getInstance().isMachineBusy()
                && FragmentFactory.curPage == FragmentEnum.ChooseCupNumFragment
                && !ApplicationConstance.getInstance().isHasCoffeeSelected()
                && CheckCurMachineState.getInstance().getMachineState().isCupShelfRightPlace();*/

        if (canClean
                && System.currentTimeMillis() - ApplicationConstance.getInstance().getLastClearMachineTime() > CLEAR_MACHINE_PERIOD) {

            MyLog.W(TAG, "clearMachine");

            List<Integer> moduleIds = new ArrayList<>();
            moduleIds.add(ClearMachine.Beater_1);
            moduleIds.add(ClearMachine.Beater_2);
            moduleIds.add(ClearMachine.Beater_3);
            //    moduleIds.add(ClearMachine.BurstBubble);
            ClearMachine.clearMachineForNeed(mInstance, moduleIds);
        }
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

    private void destroyTimerTask() {

        if (mTimer != null) {

            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {

            mTimerTask = null;
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        MyLog.d(TAG, "任务摧毁");
        destroyTimerTask();
        mInstance = null;
    }


    public void sendStateMsg() {
        MqttMessage message = new MqttMessage();
        message.setQos(1);
        message.setRetained(false);


        // msg.put("stateBag",);

        String msg = JsonUtil.mapToJson(getMsg());
        Log.e(TAG, "State is:" + msg);
        message.setPayload(msg.getBytes());


        if (client != null) {  //为了防止 在订阅之前 被调用时会 抛出client为空的异常
            if (!isConnected()) {  //未连接 则重连
                Log.e(TAG, " not connected and do reSubMqtt");
                ReSubMqtt();
            }

            MqttTopic topic = client.getTopic("server/coffee/" + MachineConfig.getMachineCode());

            try {
                Log.e(TAG, "start publish message");
                topic.publish(message);
            } catch (MqttException e) {
                Log.e(TAG, "send error " + e.getMessage() + client.isConnected());

                e.printStackTrace();

            }


        } else {
            Log.e(TAG, "client is null");
        }

    }

    private Map<String, Object> getMsg() {
        Map<String, Object> msg = new HashMap<>();
        msg.put("msgId", UUID.randomUUID().toString());
        msg.put("machineCode", MachineConfig.getMachineCode());
        msg.put("pageType", FragmentFactory.getInstance().getPageType(FragmentFactory.curPage));
        msg.put("msgType", "runningStateType");
        msg.put("sendTime", SecondToDate.getDateToString(System.currentTimeMillis()));
        Log.d(TAG, SecondToDate.getDateToString(System.currentTimeMillis()));
        msg.put("networkType", MachineConfig.getNetworkType());
        CoffMsger msger = CoffMsger.getInstance();
        MachineState state = msger.getLastMachineState();
        Result result = state.getResult();
        if (result.getCode() == Result.SUCCESS) {
            if (state.hasCupOnShelf()) {
                msg.put("cupHolderState", 1);

            } else {
                msg.put("cupHolderState", 0);
            }
            if (state.hasCup()) {
                msg.put("cupHouseState", 1);
            } else {
                msg.put("cupHouseState", 0);
            }
            msg.put("boilerTemperature", (int) state.getPotTemp());
            msg.put("boilerPressure", state.getPotPressure());
            if (state.isFrontDoorOpen()) {
                msg.put("doorState", 1);
            } else {
                msg.put("doorState", 0);
            }
            if (state.isLittleDoorOpen()) {
                msg.put("cupDoorState", 1);
            } else {
                msg.put("cupDoorState", 0);
            }
            msg.put("driverVersion", state.getVersion());
            Log.d(TAG, "stateCode is " + state.getMajorState().getStateCode() + " HighErr_byte is " + state.getMajorState().getHighErr_byte());
            switch (state.getMajorState().getStateCode()) {

                case 0:
                    //    Log.d(TAG, "0--current state is " + DataSwitcher.byte2Hex(state.getMajorState().getHighErr_byte()));
                    msg.put("errCode", "00");
                    break;
                case 0x0a:
                    //   Log.d(TAG, "0a--current state is " + state.getMajorState().getStateCode() + "and crrent HighErr_byte is " + DataSwitcher.byte2Hex(state.getMajorState().getHighErr_byte()));
                    // msg.put("errCode", "" + DataSwitcher.byte2Hex(state.getMajorState().getHighErr_byte()));
                    msg.put("errCode", "" + JinzhiSwitcher.byte2Hex(state.getMajorState().getHighErr_byte()));
                    break;
                default:
                    //    Log.d(TAG, "default--current state is " + state.getMajorState().getStateCode() + "and crrent HighErr_byte is " + DataSwitcher.byte2Hex(state.getMajorState().getHighErr_byte()));
                    //  msg.put("errCode", "" + DataSwitcher.byte2Hex(state.getMajorState().getHighErr_byte()));
                    msg.put("errCode", "" + state.getMajorState().getHighErr_byte());
                    break;
            }
            List<stateBean> stateBag = new ArrayList<>();
            stateBean stateBean1 = new stateBean();
            stateBean1.setGroup("转杯机构");
            List<StateItemBean> items = new ArrayList<>();

            StateItemBean itemDoorState = new StateItemBean();
            itemDoorState.setName("前门状态");
            if (state.isFrontDoorOpen()) {//前门开
                itemDoorState.setValue("A");
                itemDoorState.setNormal(0);//为0不正常
            } else {//前门关
                itemDoorState.setValue("B");
                itemDoorState.setNormal(1);//为0不正常
            }
            openAndCloseBean openAndCloseBean1 = new openAndCloseBean();
            openAndCloseBean1.setA("开");
            openAndCloseBean1.setB("关");
            itemDoorState.setMeaning(openAndCloseBean1);
            items.add(itemDoorState);

            StateItemBean itemcupHouseState = new StateItemBean();
            itemcupHouseState.setName("杯仓状态");
            if (state.hasCup()) {
                itemcupHouseState.setValue("A");
                itemcupHouseState.setNormal(1);
            } else {
                itemcupHouseState.setValue("B");
                itemcupHouseState.setNormal(0);
            }
            openAndCloseBean openAndCloseBean2 = new openAndCloseBean();
            openAndCloseBean2.setA("有杯");
            openAndCloseBean2.setB("无杯");
            itemcupHouseState.setMeaning(openAndCloseBean2);
            items.add(itemcupHouseState);

            StateItemBean itemcupHolderState = new StateItemBean();
            itemcupHolderState.setName("杯架状态");
            if (state.hasCupOnShelf()) {
                itemcupHolderState.setValue("A");
            } else {
                itemcupHolderState.setValue("B");
            }
            itemcupHolderState.setNormal(1);
            openAndCloseBean openAndCloseBean3 = new openAndCloseBean();
            openAndCloseBean3.setA("有杯");
            openAndCloseBean3.setB("无杯");
            itemcupHolderState.setMeaning(openAndCloseBean3);
            items.add(itemcupHolderState);
            stateBean1.setItems(items);
            stateBag.add(stateBean1);

            stateBean stateBean2 = new stateBean();
            stateBean2.setGroup("锅炉机构");
            List<StateItemBean> items2 = new ArrayList<>();
            StateItemBean boilerTemperature = new StateItemBean();
            boilerTemperature.setName("锅炉温度");
            boilerTemperature.setValue(String.valueOf(state.getPotTemp()));
            if (state.getPotTemp() > 120) {
                boilerTemperature.setNormal(0);
            } else {
                boilerTemperature.setNormal(1);
            }
            boilerTemperature.setMeaning("℃");
            items2.add(boilerTemperature);


            StateItemBean boilerTemperature2 = new StateItemBean();
            boilerTemperature2.setName("锅炉温度2");
            boilerTemperature2.setValue(String.valueOf(state.getPot2Temp()));
            if (state.getPotTemp() > 120) {
                boilerTemperature2.setNormal(0);
            } else {
                boilerTemperature2.setNormal(1);
            }
            boilerTemperature2.setMeaning("℃");
            items2.add(boilerTemperature2);

            StateItemBean boilerPressure = new StateItemBean();
            boilerPressure.setName("锅炉压力");
            boilerPressure.setValue(String.valueOf(state.getPotPressure()));
            if (Integer.parseInt(boilerPressure.getValue()) > 12000) {
                boilerPressure.setNormal(0);
            } else {
                boilerPressure.setNormal(1);
            }
            boilerPressure.setMeaning("pa");
            items2.add(boilerPressure);

            StateItemBean boilerPressure2 = new StateItemBean();
            boilerPressure2.setName("锅炉压力2");
            boilerPressure2.setValue(String.valueOf(state.getPot2Pressure()));
            if (Integer.parseInt(boilerPressure2.getValue()) > 12000) {
                boilerPressure2.setNormal(0);
            } else {
                boilerPressure2.setNormal(1);
            }
            boilerPressure2.setMeaning("pa");
            items2.add(boilerPressure2);

            stateBean2.setItems(items2);
            stateBag.add(stateBean2);

            stateBean stateBean3 = new stateBean();
            stateBean3.setGroup("搅拌电机状态");
            List<StateItemBean> items3 = new ArrayList<>();
            StateItemBean StirOn1 = new StateItemBean();
            StirOn1.setName("搅拌电机1");
            if (state.isStirOn(0)) {
                StirOn1.setValue("A");
                StirOn1.setNormal(1);
            } else {
                StirOn1.setValue("B");
                StirOn1.setNormal(1);
            }
            openAndCloseBean openAndCloseBeanOne = new openAndCloseBean();
            openAndCloseBeanOne.setA("工作");
            openAndCloseBeanOne.setB("未工作");
            StirOn1.setMeaning(openAndCloseBeanOne);
            items3.add(StirOn1);

            StateItemBean StirOn2 = new StateItemBean();
            StirOn2.setName("搅拌电机2");
            if (state.isStirOn(1)) {
                StirOn2.setValue("A");
                StirOn2.setNormal(1);
            } else {
                StirOn2.setValue("B");
                StirOn2.setNormal(1);
            }
            openAndCloseBean openAndCloseBeanTwo = new openAndCloseBean();
            openAndCloseBeanTwo.setA("工作");
            openAndCloseBeanTwo.setB("未工作");
            StirOn2.setMeaning(openAndCloseBeanTwo);
            items3.add(StirOn2);

            StateItemBean StirOn3 = new StateItemBean();
            StirOn3.setName("搅拌电机3");
            if (state.isStirOn(2)) {
                StirOn3.setValue("A");
                StirOn3.setNormal(1);
            } else {
                StirOn3.setValue("B");
                StirOn3.setNormal(1);
            }
            openAndCloseBean openAndCloseBeanThre = new openAndCloseBean();
            openAndCloseBeanThre.setA("工作");
            openAndCloseBeanThre.setB("未工作");
            StirOn3.setMeaning(openAndCloseBeanThre);
            items3.add(StirOn3);

            stateBean3.setItems(items3);
            stateBag.add(stateBean3);

            stateBean stateBean5 = new stateBean();
            stateBean5.setGroup("料盒电机状态");
            List<StateItemBean> items5 = new ArrayList<>();
            StateItemBean stateItemBean21 = new StateItemBean();
            stateItemBean21.setName("料盒电机1");
            if (state.isSecondSetSensorOn(0)) {
                stateItemBean21.setValue("A");
                stateItemBean21.setNormal(1);
            } else {
                stateItemBean21.setValue("B");
                stateItemBean21.setNormal(1);
            }
            openAndCloseBean openAndCloseBean21 = new openAndCloseBean();
            openAndCloseBean21.setA("工作");
            openAndCloseBean21.setB("未工作");
            stateItemBean21.setMeaning(openAndCloseBean21);
            items5.add(stateItemBean21);


            StateItemBean stateItemBean22 = new StateItemBean();
            stateItemBean22.setName("料盒电机2");
            if (state.isSecondSetSensorOn(1)) {
                stateItemBean22.setValue("A");
                stateItemBean22.setNormal(1);
            } else {
                stateItemBean22.setValue("B");
                stateItemBean22.setNormal(1);
            }
            openAndCloseBean openAndCloseBean22 = new openAndCloseBean();
            openAndCloseBean22.setA("工作");
            openAndCloseBean22.setB("未工作");
            stateItemBean22.setMeaning(openAndCloseBean22);
            items5.add(stateItemBean22);

            StateItemBean stateItemBean23 = new StateItemBean();
            stateItemBean22.setName("料盒电机3");
            if (state.isSecondSetSensorOn(2)) {
                stateItemBean22.setValue("A");
                stateItemBean22.setNormal(1);
            } else {
                stateItemBean22.setValue("B");
                stateItemBean22.setNormal(1);
            }
            openAndCloseBean openAndCloseBean23 = new openAndCloseBean();
            openAndCloseBean23.setA("工作");
            openAndCloseBean23.setB("未工作");
            stateItemBean23.setMeaning(openAndCloseBean23);
            items5.add(stateItemBean23);

            StateItemBean stateItemBean24 = new StateItemBean();
            stateItemBean24.setName("料盒电机4");
            if (state.isSecondSetSensorOn(3)) {
                stateItemBean24.setValue("A");
                stateItemBean24.setNormal(1);
            } else {
                stateItemBean24.setValue("B");
                stateItemBean24.setNormal(1);
            }
            openAndCloseBean openAndCloseBean24 = new openAndCloseBean();
            openAndCloseBean24.setA("工作");
            openAndCloseBean24.setB("未工作");
            stateItemBean24.setMeaning(openAndCloseBean24);
            items5.add(stateItemBean24);

            StateItemBean stateItemBean25 = new StateItemBean();
            stateItemBean25.setName("料盒电机5");
            if (state.isSecondSetSensorOn(4)) {
                stateItemBean25.setValue("A");
                stateItemBean25.setNormal(1);
            } else {
                stateItemBean25.setValue("B");
                stateItemBean25.setNormal(1);
            }
            openAndCloseBean openAndCloseBean25 = new openAndCloseBean();
            openAndCloseBean25.setA("工作");
            openAndCloseBean25.setB("未工作");
            stateItemBean25.setMeaning(openAndCloseBean25);
            items5.add(stateItemBean25);

            StateItemBean stateItemBean26 = new StateItemBean();
            stateItemBean26.setName("料盒电机6");
            if (state.isSecondSetSensorOn(5)) {
                stateItemBean26.setValue("A");
                stateItemBean26.setNormal(1);
            } else {
                stateItemBean26.setValue("B");
                stateItemBean26.setNormal(1);
            }
            openAndCloseBean openAndCloseBean26 = new openAndCloseBean();
            openAndCloseBean26.setA("工作");
            openAndCloseBean26.setB("未工作");
            stateItemBean26.setMeaning(openAndCloseBean26);
            items5.add(stateItemBean26);
            stateBean5.setItems(items5);
            stateBag.add(stateBean5);

            stateBean stateBean6 = new stateBean();
            stateBean5.setGroup("ES/FB电机运行状态");
            List<StateItemBean> items6 = new ArrayList<>();
            StateItemBean stateItemBean31 = new StateItemBean();
            stateItemBean31.setName("ES挤饼电机");
            if (state.isThirdSetMotorOn(0)) {
                stateItemBean31.setValue("A");
                stateItemBean31.setNormal(1);
            } else {
                stateItemBean31.setValue("B");
                stateItemBean31.setNormal(1);
            }
            openAndCloseBean openAndCloseBean31 = new openAndCloseBean();
            openAndCloseBean31.setA("工作");
            openAndCloseBean31.setB("未工作");
            stateItemBean31.setMeaning(openAndCloseBean31);
            items6.add(stateItemBean31);

            StateItemBean stateItemBean32 = new StateItemBean();
            stateItemBean32.setName("ES密封电机");
            if (state.isThirdSetMotorOn(1)) {
                stateItemBean32.setValue("A");
                stateItemBean32.setNormal(1);
            } else {
                stateItemBean32.setValue("B");
                stateItemBean32.setNormal(1);
            }
            openAndCloseBean openAndCloseBean32 = new openAndCloseBean();
            openAndCloseBean32.setA("工作");
            openAndCloseBean32.setB("未工作");
            stateItemBean32.setMeaning(openAndCloseBean32);
            items6.add(stateItemBean32);

            StateItemBean stateItemBean33 = new StateItemBean();
            stateItemBean33.setName("FB刮片电机");
            if (state.isThirdSetMotorOn(2)) {
                stateItemBean33.setValue("A");
                stateItemBean33.setNormal(1);
            } else {
                stateItemBean33.setValue("B");
                stateItemBean33.setNormal(1);
            }
            openAndCloseBean openAndCloseBean33 = new openAndCloseBean();
            openAndCloseBean33.setA("工作");
            openAndCloseBean33.setB("未工作");
            stateItemBean33.setMeaning(openAndCloseBean33);
            items6.add(stateItemBean33);

            StateItemBean stateItemBean34 = new StateItemBean();
            stateItemBean34.setName("FB密封电机");
            if (state.isThirdSetMotorOn(3)) {
                stateItemBean34.setValue("A");
                stateItemBean34.setNormal(1);
            } else {
                stateItemBean34.setValue("B");
                stateItemBean34.setNormal(1);
            }
            openAndCloseBean openAndCloseBean34 = new openAndCloseBean();
            openAndCloseBean34.setA("工作");
            openAndCloseBean34.setB("未工作");
            stateItemBean34.setMeaning(openAndCloseBean34);
            items6.add(stateItemBean34);

            stateBean6.setItems(items6);
            stateBag.add(stateBean6);

            stateBean stateBean7 = new stateBean();
            stateBean7.setGroup("杯机构/门机构电机");
            List<StateItemBean> items7 = new ArrayList<>();
            StateItemBean stateItemBean41 = new StateItemBean();
            stateItemBean41.setName("分杯电机");
            if (state.isForthSetMotorOn(0)) {
                stateItemBean41.setValue("A");
                stateItemBean41.setNormal(1);
            } else {
                stateItemBean41.setValue("B");
                stateItemBean41.setNormal(1);
            }
            openAndCloseBean openAndCloseBean41 = new openAndCloseBean();
            openAndCloseBean41.setA("工作");
            openAndCloseBean41.setB("未工作");
            stateItemBean41.setMeaning(openAndCloseBean41);
            items7.add(stateItemBean41);

            StateItemBean stateItemBean42 = new StateItemBean();
            stateItemBean42.setName("杯桶电机");
            if (state.isForthSetMotorOn(1)) {
                stateItemBean42.setValue("A");
                stateItemBean42.setNormal(1);
            } else {
                stateItemBean42.setValue("B");
                stateItemBean42.setNormal(1);
            }
            openAndCloseBean openAndCloseBean42 = new openAndCloseBean();
            openAndCloseBean42.setA("工作");
            openAndCloseBean42.setB("未工作");
            stateItemBean42.setMeaning(openAndCloseBean42);
            items7.add(stateItemBean42);

            StateItemBean stateItemBean43 = new StateItemBean();
            stateItemBean43.setName("运杯电机");
            if (state.isForthSetMotorOn(2)) {
                stateItemBean43.setValue("A");
                stateItemBean43.setNormal(1);
            } else {
                stateItemBean43.setValue("B");
                stateItemBean43.setNormal(1);
            }
            openAndCloseBean openAndCloseBean43 = new openAndCloseBean();
            openAndCloseBean43.setA("工作");
            openAndCloseBean43.setB("未工作");
            stateItemBean43.setMeaning(openAndCloseBean43);
            items7.add(stateItemBean43);

            StateItemBean stateItemBean44 = new StateItemBean();
            stateItemBean44.setName("大门电机");
            if (state.isForthSetMotorOn(3)) {
                stateItemBean44.setValue("A");
                stateItemBean44.setNormal(1);
            } else {
                stateItemBean44.setValue("B");
                stateItemBean44.setNormal(1);
            }
            openAndCloseBean openAndCloseBean44 = new openAndCloseBean();
            openAndCloseBean44.setA("工作");
            openAndCloseBean44.setB("未工作");
            stateItemBean44.setMeaning(openAndCloseBean44);
            items7.add(stateItemBean44);

            StateItemBean stateItemBean45 = new StateItemBean();
            stateItemBean45.setName("小门电机");
            if (state.isForthSetMotorOn(4)) {
                stateItemBean45.setValue("A");
                stateItemBean45.setNormal(1);
            } else {
                stateItemBean45.setValue("B");
                stateItemBean45.setNormal(1);
            }
            openAndCloseBean openAndCloseBean45 = new openAndCloseBean();
            openAndCloseBean45.setA("工作");
            openAndCloseBean45.setB("未工作");
            stateItemBean45.setMeaning(openAndCloseBean45);
            items7.add(stateItemBean45);

            stateBean7.setItems(items7);
            stateBag.add(stateBean7);

            stateBean stateBean4 = new stateBean();
            stateBean4.setGroup("落料机构");
            List<StateItemBean> items4 = new ArrayList<>();
            StateItemBean BeanState = new StateItemBean();
            BeanState.setName("咖啡豆仓");
            if (state.isBeanEnough()) {
                BeanState.setValue("A");
                BeanState.setNormal(1);
            } else {
                BeanState.setValue("B");
                BeanState.setNormal(0);
            }
            openAndCloseBean Bean_openAndCloseBean = new openAndCloseBean();
            Bean_openAndCloseBean.setA("充足");
            Bean_openAndCloseBean.setB("缺豆");
            BeanState.setMeaning(Bean_openAndCloseBean);
            items4.add(BeanState);

            StateItemBean WaterContainerState = new StateItemBean();
            WaterContainerState.setName("污水仓");
            if (state.isWasteContainerFull()) {
                WaterContainerState.setValue("A");
                WaterContainerState.setNormal(0);
            } else {
                WaterContainerState.setValue("B");
                WaterContainerState.setNormal(1);
            }
            openAndCloseBean WaterContainerOpenAndCloseBean = new openAndCloseBean();
            WaterContainerOpenAndCloseBean.setA("已满");
            WaterContainerOpenAndCloseBean.setB("未满");
            WaterContainerState.setMeaning(WaterContainerOpenAndCloseBean);
            items4.add(WaterContainerState);

            StateItemBean waterState = new StateItemBean();
            waterState.setName("净水仓");
            if (state.isWaterEnough()) {
                waterState.setValue("A");
                waterState.setNormal(1);
            } else {
                waterState.setValue("B");
                waterState.setNormal(0);
            }
            openAndCloseBean waterOpenAndCloseBean = new openAndCloseBean();
            waterOpenAndCloseBean.setA("充足");
            waterOpenAndCloseBean.setB("缺水");
            waterState.setMeaning(waterOpenAndCloseBean);
            items4.add(waterState);

            stateBean4.setItems(items4);
            stateBag.add(stateBean4);

            stateBean stateBean8 = new stateBean();
            stateBean8.setGroup("第一组传感器检测");
            List<StateItemBean> items8 = new ArrayList<>();
            StateItemBean FirstSetSensorOn2 = new StateItemBean();
            FirstSetSensorOn2.setName("净水桶检测2传感器");
            if (state.isFirstSetSensorOn(2)) {
                FirstSetSensorOn2.setValue("A");
                FirstSetSensorOn2.setNormal(1);
            } else {
                FirstSetSensorOn2.setValue("B");
                FirstSetSensorOn2.setNormal(0);
            }
            openAndCloseBean openAndCloseBeanFirstSetSensorOn2 = new openAndCloseBean();
            openAndCloseBeanFirstSetSensorOn2.setA("到位");
            openAndCloseBeanFirstSetSensorOn2.setB("离开");
            FirstSetSensorOn2.setMeaning(openAndCloseBeanFirstSetSensorOn2);
            items8.add(FirstSetSensorOn2);

            StateItemBean FirstSetSensorOn3 = new StateItemBean();
            FirstSetSensorOn3.setName("滴水hall传感器");
            if (state.isFirstSetSensorOn(3)) {
                FirstSetSensorOn3.setValue("A");
                FirstSetSensorOn3.setNormal(1);
            } else {
                FirstSetSensorOn3.setValue("B");
                FirstSetSensorOn3.setNormal(0);
            }
            openAndCloseBean openAndCloseBeanFirstSetSensorOn3 = new openAndCloseBean();
            openAndCloseBeanFirstSetSensorOn3.setA("有");
            openAndCloseBeanFirstSetSensorOn3.setB("无");
            FirstSetSensorOn3.setMeaning(openAndCloseBeanFirstSetSensorOn3);
            items8.add(FirstSetSensorOn3);

            StateItemBean FirstSetSensorOn5 = new StateItemBean();
            FirstSetSensorOn5.setName("水盒探针传感器");
            if (state.isFirstSetSensorOn(5)) {
                FirstSetSensorOn5.setValue("A");
                FirstSetSensorOn5.setNormal(1);
            } else {
                FirstSetSensorOn5.setValue("B");
                FirstSetSensorOn5.setNormal(0);
            }
            openAndCloseBean openAndCloseBeanFirstSetSensorOn5 = new openAndCloseBean();
            openAndCloseBeanFirstSetSensorOn5.setA("有");
            openAndCloseBeanFirstSetSensorOn5.setB("无");
            FirstSetSensorOn5.setMeaning(openAndCloseBeanFirstSetSensorOn5);
            items8.add(FirstSetSensorOn5);

            StateItemBean FirstSetSensorOn7 = new StateItemBean();
            FirstSetSensorOn7.setName("FB密封传感器2");
            if (state.isFirstSetSensorOn(7)) {
                FirstSetSensorOn7.setValue("A");
                FirstSetSensorOn7.setNormal(1);
            } else {
                FirstSetSensorOn7.setValue("B");
                FirstSetSensorOn7.setNormal(0);
            }
            openAndCloseBean openAndCloseBeanFirstSetSensorOn7 = new openAndCloseBean();
            openAndCloseBeanFirstSetSensorOn7.setA("有");
            openAndCloseBeanFirstSetSensorOn7.setB("无");
            FirstSetSensorOn7.setMeaning(openAndCloseBeanFirstSetSensorOn7);
            items8.add(FirstSetSensorOn7);

            stateBean8.setItems(items8);
            stateBag.add(stateBean8);


            msg.put("stateBag", stateBag);
        /*    if (stateBag.size() != 0) {
                stateBag.clear();//清空列表释放内存

            }*/
        } else {

            msg.put("cupHolderState", null);


            msg.put("boilerTemperature", null);
            msg.put("boilerPressure", null);

            msg.put("doorState", null);

            msg.put("cupHouseState", null);
            msg.put("cupDoorState", null);

            msg.put("driverVersion", "1.0.0");
            msg.put("errCode", "");
            // }
            msg.put("stateBag", null);
        }
        msg.put("clientVersion", HomeActivity.getInstance().getVersion());
        msg.put("mediaVersion", "1.0.0");

        //  Log.d(TAG, msg.toString());
        return msg;
    }

    /**
     * 发送本地交易数据至服务器
     */
    private void sendLocDealMsg() {

        QRMsger qrMsger = new QRMsger();
        List<DealRecorder> dealRecorderList = DealOrderInfoManager.getInstance(mInstance).getLocalTableDatas();
        for (int i = 0; i < dealRecorderList.size(); i++) {
            DealRecorder dealRecorder = dealRecorderList.get(i);
            if (dealRecorder.isReportSuccess()) {
                continue;
            } else {
                if (dealRecorder.getUploadCount() >= 1 && dealRecorder.getUploadCount() <= 5) {

                    DealRecorder newDealRecorder = qrMsger.reportTradeToServer(dealRecorder, dealRecorder.getBunkers());
                    MyLog.d(TAG, "order= " + dealRecorder.getOrder() + ", report to server into taskservice");

                    //更新本地交易记录
                    DealOrderInfoManager.getInstance(mInstance).update(newDealRecorder);
                }

            }
        }

    }


    @Override
    public void onSuccess(IMqttToken iMqttToken) {

    }

    @Override
    public void onFailure(IMqttToken iMqttToken, Throwable throwable) {

    }
}
